<?php

	/*
	* Page to show the most viewed practices, call from menu
	* */

	global $CONFIG;
	gatekeeper();
	require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/engine/start.php");
	
	//The offset is fetched to page through the results, if none set to 0
	if(isset($_GET['offset'])){
		$offset=$_GET['offset'];
	}
	else{
		$offset=0;
	}

	$entities = array();
	$showed = 10; //number of practices to display per page

	
	
	//Get mycase guid entities with a view.
	$query = "SELECT e.guid FROM " . $CONFIG->dbprefix . "metadata AS m JOIN " . $CONFIG->dbprefix . "entities e ON e.guid = m.entity_guid  JOIN " . $CONFIG->dbprefix . "entity_subtypes st ON e.subtype=st.id AND st.subtype='mycase' JOIN " . $CONFIG->dbprefix . "metastrings ms ON ms.id = m.name_id WHERE ms.string = 'views'";

	$result = get_data($query);
		
	
	//For each subtype myCASE entity, get it
	foreach ($result AS $anGuid){

		$entities[] = get_entity($anGuid->guid);	
	}
	
	//Function to compare practices in function of their views
	function cmp($ent1, $ent2){
		
    if ($ent1->views == $ent2->views) {
        return 0;
    }
    
		return ($ent1->views > $ent2->views) ? -1 : 1;
	}

	//sort the entities in function of the times they have been seen
	usort($entities, "cmp");
	

	$page_owner = page_owner_entity();
		
	if ($page_owner === false || is_null($page_owner)) {
		$page_owner = $_SESSION['user'];
		set_page_owner($_SESSION['guid']);
	}

	$area2 = elgg_view_title(elgg_echo('mycase:mostViewed'));
	//Prepare the result to page through
	$entitiesPag=array_slice($entities, $offset, $offset+$showed);
	$area2 .= elgg_view_entity_list($entitiesPag, count($entities), $offset, $showed, FALSE, TRUE, TRUE);

      
	set_context('search');
		
	global $CONFIG;
	$categories = elgg_view('categories/list', array('baseurl' => $CONFIG->wwwroot . 'search/?subtype=mycase&tagtype=universal_categories&tag=', 'owner_guid' => $page_owner->guid));
	if(!empty($categories))
	{
		$area3 .= '<div class="contentWrapper">' . $categories . '</div>';
	}
	
	//Show Tag Cloud
	$area3 .= elgg_view('mycase/cloudTag');

	$body = elgg_view_layout("two_column_left_sidebar", '', $area2, $area3);		
	set_context('mycase');
	page_draw(elgg_echo('mycase:mostViewed'),$body);
		
?>
